<template>
    <div class="user-data">
        <ZwSearchForm row-num="4" :option="searchOption" :default-expand="false" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            :select-all-group="true"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @dataChange="onDataChange"
            @select-all-change="onSelectAllChange"
            @selectAllTotal="selectAllTotal">
            <template #headerOperate>
                <el-button v-auth="'USER_EXPORT'" :disabled="disabled()" @click="exportData">导出</el-button>
            </template>
        </ZwTable>
    </div>
    <FissionDetail ref="fissionDetailRef" />
    <HintText ref="hintTextRef" :hint-text="hintText" @submit="submit"></HintText>
</template>

<script setup lang="tsx">
import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
// 查询组件
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
// 引入表格组件
import ZwTable from '@/components/zw/table1.0/Table';
// 群聊信息tooltip组件
import TableTooltip from './TableTooltip.vue';
// 奖品明细弹框组件
import FissionDetail from './FissionDetail.vue';
// 按钮的二次确认弹框提示文案组件
import HintText from './HintText.vue';
// 用户信息组件
import UserInfo from './UserInfo.vue';

// 引入搜索配置项
import { userConfig } from './searchConfig';

import { getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';

// 接口
import { userList, numberExport, userLimit } from '@/api/smartMarketing/drainage/groupFission';

import { ElMessage, ElAvatar, ElTooltip } from 'element-plus';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';
// import { spawn } from 'child_process';

const route = useRoute();
// 表格ref
const tableRef = ref();
// 奖品明细ref
const fissionDetailRef = ref();
// 二次提示弹框文案ref
const hintTextRef = ref();
// 获取路由参数
const { id } = route.query;
// 弹框文案
const hintText = ref('');
// 表格全选
const selectTableTotal = ref(0);
// 表格全选取消
const cancleAllArray = ref([]);
// 表格当前页全选
const currentSelectArr = ref([]);
// 所有的数据
const totalAll = ref([]);
// 查询组件配置项
const searchOption = computed(() => {
    return userConfig(id);
});

// 表格配置项
const tableOption = reactive([
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'number',
        label: '编号',
        width: 55
    },
    {
        prop: 'avatar',
        label: '用户信息',
        width: 220,
        render({ row }: unknown) {
            return (
                <div>
                    <UserInfo
                        limit={6}
                        name={row.nickname || row.unionid}
                        avatar={row.external_userid == '' ? '' : row.avatar}></UserInfo>
                </div>
            );
        }
    },
    {
        prop: 'grade',
        label: '裂变等级',
        width: 100,
        render({ row }: unknown) {
            return <span>{row.grade || '--'}</span>;
        }
    },
    {
        prop: 'fission_num',
        label: '裂变人数',
        width: 100
    },
    {
        prop: 'help_num',
        label: '助力人数',
        width: 100
    },
    {
        prop: 'invalid_num',
        label: '失效人数',
        width: 100
    },
    {
        prop: 'step_level',
        label: '达成阶梯等级',
        width: 120,
        render({ row }: unknown) {
            return <span>{row.step_level || '--'}</span>;
        }
    },
    {
        prop: 'receive_step_level',
        label: '领奖阶梯等级',
        width: 120,
        render({ row }: unknown) {
            return <span>{row.receive_step_level || '--'}</span>;
        }
    },
    {
        prop: 'part_time',
        label: '参与时间',
        width: 180
    },
    {
        prop: 'is_group_member',
        label: '是否群成员',
        width: 100,
        render({ row }: unknown) {
            return <span>{row.is_group_member === 1 ? '否' : '是'}</span>;
        }
    },
    {
        prop: 'is_new',
        label: '是否新客户',
        width: 100,
        render({ row }: unknown) {
            return <span>{row.is_new === 1 ? '否' : '是'}</span>;
        }
    },
    {
        prop: 'is_limit',
        label: '是否限制',
        width: 100,
        render({ row }: unknown) {
            return <span>{row.is_limit === 1 ? '否' : '是'}</span>;
        }
    },
    {
        prop: 'group_info',
        label: '群聊信息',
        width: 580,
        render({ row }: unknown) {
            return <TableTooltip groupInfo={row.group_info}></TableTooltip>;
        }
    },
    {
        prop: 'prev_user_avatar',
        label: '上级用户',
        width: 150,
        render({ row }: unknown) {
            return <UserInfo name={row.prev_user_name} avatar={row.prev_user ? row.prev_user_avatar : ''}></UserInfo>;
        }
    },
    {
        prop: 'drainage_member_avatar',
        label: '引流成员',
        width: 150,
        render({ row }: unknown) {
            return (
                <UserInfo
                    name={row.drainage_member_name}
                    avatar={row.drainage_member ? row.drainage_member_avatar : ''}></UserInfo>
            );
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 150,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '裂变明细',
                authCode: 'FISSION_DETATIL',
                isRender: ({ row }: any) => row.external_userid !== '',
                click: (row: any) => handle(row, 1)
            },
            {
                name: '限制',
                authCode: 'USER_DATA_LIMIT',
                isRender: ({ row }: any) => row.external_userid !== '' && row.is_limit === 1,
                click: (row: any) => handle(row, 2)
            },
            {
                name: '取消限制',
                authCode: 'USER_DATA_CANCEL_LIMIT',
                isRender: ({ row }: any) => row.external_userid !== '' && row.is_limit === 2,
                click: (row: any) => handle(row, 3)
            }
        ]
    }
]);
// 表格参数
const defaultParams = reactive({
    id, // 活动id
    name: '', // 用户昵称
    fission_level: '', // 裂变等级
    step_level: '', // 达成阶梯等级
    receive_step_level: [], // 领奖阶梯等级
    is_limit: 'all', // 是否限制
    is_new: 'all', // 是否新客户
    is_group_member: 'all', // 是否群成员
    join_time: [], // 入群时间
    quit_time: [] // 退群时间
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const getRowKey = (row: any) => {
    return row.id;
};
const fetchApi = () => {
    // 获取文件列表
    return userList;
};

// 表格当前页全选
const onSelectAll = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 选择表格数据
const onSelect = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 改变选项
const onDataChange = (v: any) => {
    totalAll.value = v.total;

    // 处理编号的顺序
    const { page = 1, page_size = 15 } = v;
    v.data.forEach((item: any, index: number) => {
        item.number = page_size * (page - 1) + index + 1;
    });
};
// 选项的变更
const onSelectionChange = (v: any) => {
    currentSelectArr.value = getSetionId('id', v);
};
// 全选的改变
const onSelectAllChange = (v: any) => {
    cancleAllArray.value = v;
};
// 选中表格所有数据
const selectAllTotal = (v: any) => {
    selectTableTotal.value = v;
};
// 是否禁用批量操作
const disabled = () => {
    if (currentSelectArr.value.length > 0 || selectTableTotal.value > 0) {
        return false;
    } else {
        return true;
    }
};

// 查询
const search = (v: any) => {
    tableRef.value.clearAllSelect();
    tableRef.value.clearSelection();
    state.searchParams = deepCopy({ id, ...v });
};
// 清空查询条件
const reset = (v: any) => {
    tableRef.value.clearSelection();
    tableRef.value.clearAllSelect();
    state.searchParams = deepCopy({ id, ...v });
};

// 导出
const exportData = e => {
    let params = {
        ...state.searchParams,
        select_type: 1,
        contain_ids: currentSelectArr.value
    };
    if (tableRef.value.getIsSelectAll()) {
        params = {
            exclude_ids: cancleAllArray.value,
            ...state.searchParams,
            select_type: 2
        };
    }
    numberExport(params).then(() => {
        parabolaAnimation(e);
        ShowTaskMessage('导出异步任务创建成功');
        tableRef.value.clearSelection();
        tableRef.value.clearAllSelect();
    });
};

// 表格操作，1——裂变详情，2——限制，3——取消限制
const handle = (row: any, type: any) => {
    switch (type) {
        case 1:
            fissionDetailRef.value.open(id, row.external_userid);
            break;
        case 2:
            hintText.value = '确定要将该用户加入限制名单吗？限制后不能参与活动，奖品会失效。';
            hintTextRef.value.open(hintText.value, row, 1);
            break;
        case 3:
            hintText.value = '确定要将该用户取消限制吗？';
            hintTextRef.value.open(hintText.value, row, 2);
            break;
    }
};

// 限制和取消限制
const submit = (row: any, type: number) => {
    const params = {
        id,
        type,
        external_userid: row.external_userid
    };
    userLimit(params)
        .then(() => {
            ElMessage.success('操作成功');
            tableRef.value.reload();
        })
        .catch((error: any) => {
            ElMessage.error(error);
        });
};
</script>

<style lang="scss" scoped>
.user-data {
    margin-top: 8px;

    :deep(.user-info) {
        display: flex;
        align-items: center;
    }

    :deep(.user-name) {
        font-weight: 400;
        max-width: 100px;
        margin-left: 8px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
</style>
